package server

import (
	"battle-server/engine"
	"context"
	"fmt"
	"log"
	pb "proto"
	"sync"
	"time"
)

type BattleServer struct {
	pb.UnimplementedBattleServiceServer
	battles sync.Map // battleID -> *Battle
}

type Battle struct {
	BattleID  string
	Player1   *pb.Player
	Player2   *pb.Player
	Result    *pb.BattleResult
	Completed bool
}

func NewBattleServer() *BattleServer {
	return &BattleServer{}
}

func (s *BattleServer) StartBattle(ctx context.Context, req *pb.BattleRequest) (*pb.BattleResponse, error) {
	// 生成唯一的战斗ID
	battleID := generateBattleID()

	// 创建新的战斗实例
	battle := &Battle{
		BattleID: battleID,
		Player1:  req.Player1,
		Player2:  req.Player2,
	}

	// 存储战斗信息
	s.battles.Store(battleID, battle)

	// 异步执行战斗逻辑
	go s.executeBattle(battle)

	return &pb.BattleResponse{
		Success:  true,
		Message:  "Battle started",
		BattleId: battleID,
	}, nil
}

func (s *BattleServer) GetBattleResult(ctx context.Context, req *pb.BattleResultRequest) (*pb.BattleResultResponse, error) {
	// 获取战斗信息
	battleData, exists := s.battles.Load(req.BattleId)
	if !exists {
		return &pb.BattleResultResponse{
			Success: false,
			Message: "Battle not found",
		}, nil
	}

	battle := battleData.(*Battle)
	if !battle.Completed {
		return &pb.BattleResultResponse{
			Success: false,
			Message: "Battle still in progress",
		}, nil
	}

	return &pb.BattleResultResponse{
		Success: true,
		Message: "Battle completed",
		Result:  battle.Result,
	}, nil
}

func (s *BattleServer) executeBattle(battle *Battle) {
	log.Printf("开始执行战斗 ID: %s", battle.BattleID)

	battleEngine := engine.NewBattleEngine(battle.Player1, battle.Player2)
	result := battleEngine.Execute()

	battle.Result = result
	battle.Completed = true

	log.Printf("战斗完成 ID: %s, 获胜者: %s", battle.BattleID, result.WinnerId)
}

func generateBattleID() string {
	return fmt.Sprintf("battle_%d", time.Now().UnixNano())
}
